package com.appspot.zarm.controller.operations;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.appspot.zarm.controller.RequestParameters;
import com.appspot.zarm.game.GamesStorage;

public abstract class Operation {
	
	private ServletContext servletContext;
	
	public Operation() {};
	
	public Operation(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	public abstract void execute(HttpServletRequest request, HttpServletResponse response);
	
	protected void goLayoutPage(HttpServletRequest request, HttpServletResponse response) {
		try {
			servletContext.getRequestDispatcher("/layout.jsp").forward(request, response);
		} catch (ServletException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	protected void print(HttpServletResponse response, String value) {
		response.setContentType("text/html");
		PrintWriter pw = null;
		try {
			pw = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
		pw.print(value);
	}
	
	protected GamesStorage getGamesStorage() {
		GamesStorage gs = (GamesStorage) servletContext.getAttribute(RequestParameters.GAMES_STORAGE_ATTR_NAME);
		if (gs == null) {
			gs = new GamesStorage();
			servletContext.setAttribute(RequestParameters.GAMES_STORAGE_ATTR_NAME, gs);
		}
		return gs;
	}
}
